package com.ErpCoreWeb.Report;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ErpCoreModel.Base.CCompany;
import com.ErpCoreModel.Base.CUser;
import com.ErpCoreModel.Framework.CBaseObject;
import com.ErpCoreModel.Framework.CColumn;
import com.ErpCoreModel.Framework.CTable;
import com.ErpCoreModel.Framework.ColumnType;
import com.ErpCoreModel.Framework.Util;
import com.ErpCoreModel.Report.CReport;
import com.ErpCoreModel.Report.CReportCatalog;
import com.ErpCoreModel.Report.CStatItem;
import com.ErpCoreWeb.Common.EditObject;
import com.ErpCoreWeb.Common.Global;

/**
 * Servlet implementation class EditReport
 */
@WebServlet("/EditReport")
public class EditReport extends HttpServlet {
	private static final long serialVersionUID = 1L;

	HttpServletRequest request;
	HttpServletResponse response;

    public CTable m_Table = null;
    public CCompany m_Company = null;
    public CReport m_BaseObject = null;
    /**
     * @see HttpServlet#HttpServlet()
     */
    public EditReport() {
        super();
        // TODO Auto-generated constructor stub
    }

    //初始化变量
    void initData()
    {
        if (request.getSession().getAttribute("User") == null)
        {
            try {
				response.sendRedirect("../Login.jsp");
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
            return ;
        }
		try {
			String B_Company_id = request.getParameter("B_Company_id");
			if (Global.IsNullParameter(B_Company_id))
				m_Company = Global.GetCtx(this.getServletContext())
						.getCompanyMgr().FindTopCompany();
			else
				m_Company = (CCompany) Global.GetCtx(this.getServletContext())
						.getCompanyMgr().Find(Util.GetUUID(B_Company_id));

			m_Table = m_Company.getReportCatalogMgr().getTable();

			String id = request.getParameter("id");
			if (Global.IsNullParameter(id)) {
				response.getWriter().close();
				return;
			}
			m_BaseObject = (CReport) m_Company.getReportMgr().Find(
					Util.GetUUID(id));
			if (m_BaseObject == null) {
				response.getWriter().close();
				return;
			}

			// 保存到编辑对象
			EditObject.Add(request.getSession().getId(), m_BaseObject);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doProc(request,response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doProc(request,response);
	}
	void doProc(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{

		this.request=request;
		this.response=response;

		response.setContentType("text/html;charset=UTF-8");
		request.setCharacterEncoding("UTF-8");

		//初始化变量
	    initData();
	    //
        String Action = request.getParameter("Action");
        if (Action == null) Action = "";

        if (Action.equalsIgnoreCase("GetData"))
        {
            GetData();
            return ;
        }
        else if (Action.equalsIgnoreCase("Cancel"))
        {
        	request.getSession().setAttribute("AddReport", null);
            return ;
        }
        else if (Action.equalsIgnoreCase("PostData"))
        {
        	PostData();
            //从编辑对象移除
            EditObject.Remove(request.getSession().getId(), m_BaseObject);
            return ;
        }
        else if (Action.equalsIgnoreCase("GetCondiction"))
        {
        	GetCondiction();
            return ;
        }
	}

    void GetData()
    {
		try {
			CReport Report = GetReport();
			List<CBaseObject> lstObj = Report.getStatItemMgr().GetList();
			// 按序号排序
			List<CStatItem> sortObj = new ArrayList<CStatItem>();
			for (CBaseObject obj : lstObj) {
				CStatItem StatItem = (CStatItem) obj;
				sortObj.add(StatItem);
			}
			Collections.sort(sortObj, new Comparator() {
				public int compare(Object a, Object b) {
					return ((CStatItem) a).getIdx() - ((CStatItem) b).getIdx();
				}
			});

			String sData = "";
			for (CStatItem StatItem : sortObj) {
				String sTableName = "", sColumnName = "";
				CTable table = (CTable) Global.GetCtx(this.getServletContext())
						.getTableMgr().Find(StatItem.getFW_Table_id());
				if (table != null) {
					sTableName = table.getName();
					CColumn column = (CColumn) table.getColumnMgr().Find(
							StatItem.getFW_Column_id());
					if (column != null)
						sColumnName = column.getName();
				}

				sData += String
						.format("{ \"id\": \"%s\",\"FW_Table_id\":\"%s\",\"TableName\":\"%s\",\"FW_Column_id\":\"%s\", \"ColumnName\":\"%s\", \"StatType\":\"%d\", \"StatTypeName\":\"%s\", \"Order\":\"%s\", \"OrderName\":\"%s\" },",
								StatItem.getId().toString(), StatItem
										.getFW_Table_id().toString(),
								sTableName, StatItem.getFW_Column_id()
										.toString(), sColumnName,
								(int) StatItem.getStatType().ordinal(),
								StatItem.GetStatTypeName(), (int) StatItem
										.getOrder().ordinal(), StatItem
										.GetOrderName());
			}

			sData = "[" + sData + "]";
			String sJson = String.format("{\"Rows\":%s,\"Total\":\"%d\"}",
					sData, lstObj.size());

			response.getWriter().print(sJson);

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    }
    public CReport GetReport()
    {
        return m_BaseObject;
    }

    void PostData()
    {
		try {
			String Name = request.getParameter("Name");
			String Catalog_id = request.getParameter("catalog_id");
			String GridData = request.getParameter("GridData");
			String Filter = request.getParameter("Filter");

			if (Global.IsNullParameter(Name)) {
				response.getWriter().print("名称不能空！");
				return;
			}

			GetReport().setName(Name);
			if (Global.IsNullParameter(Catalog_id))
				GetReport().setRPT_ReportCatalog_id(Util.GetUUID(Catalog_id));
			GetReport().setFilter(Filter);

			int iLastIdx = 0;
			String[] arr1 = GridData.split(";");
			for (String str1 : arr1) {
				if (str1.length() == 0)
					continue;
				iLastIdx++;

				String[] arr2 = str1.split(",");
				String id = arr2[0];
				String StatTypeName = arr2[1];
				String OrderName = arr2[2];
				CStatItem StatItem = (CStatItem) GetReport().getStatItemMgr()
						.Find(Util.GetUUID(id));
				if (StatItem != null) {
					StatItem.setIdx(iLastIdx);
					StatItem.SetStatTypeByName(StatTypeName);
					StatItem.SetOrderByName(OrderName);
				}
			}

			CUser user = (CUser) request.getSession().getAttribute("User");
			GetReport().setUpdator(user.getId());

			m_Company.getReportMgr().Update(GetReport());

			if (!m_Company.getReportMgr().Save(true)) {
				response.getWriter().print("修改失败！");
				return;
			}

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    }
    void GetCondiction()
    {
		try {
			String Table_id = request.getParameter("Table_id");
			String Column_id = request.getParameter("Column_id");
			String Val = request.getParameter("Val");

			CTable table = (CTable) Global.GetCtx(this.getServletContext())
					.getTableMgr().Find(Util.GetUUID(Table_id));
			if (table == null)
				return;
			CColumn col = (CColumn) table.getColumnMgr().Find(
					Util.GetUUID(Column_id));
			if (col == null)
				return;
			if (col.getColType() == ColumnType.int_type
					|| col.getColType() == ColumnType.long_type
					|| col.getColType() == ColumnType.numeric_type
					|| col.getColType() == ColumnType.bool_type) {
				if (Global.IsNullParameter(Val))
					Val = "0";
				else {
					Double.valueOf(Val);
					
				}
			} else {
				if (Global.IsNullParameter(Val))
					Val = "''";
				else {
					if (Val.startsWith("\'"))
						Val = "\'" + Val;
					if (Val.endsWith("\'"))
						Val += "\'";
				}
			}

			response.getWriter().print(Val);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    }

    public String GetCatalogName()
    {
        if (m_BaseObject == null)
            return "";
        CReportCatalog Catalog = (CReportCatalog)m_Company.getReportCatalogMgr().Find(m_BaseObject.getRPT_ReportCatalog_id());
        if (Catalog == null)
            return "";
        return Catalog.getName();
    }
}
